<?php

namespace App\Http\Middleware;

use App\Models\Department;
use Illuminate\Support\Facades\Auth;
use App\User;
use Illuminate\Support\Facades\Hash;
use Validator;
use Illuminate\Support\Facades\Input;
use Closure;

class CheckAge
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $validator = Validator::make(Input::all(),[
            'name' => 'required|max:20|min:5',
            'password' => 'required|max:20|min:5',
        ]);
        if($validator->fails()){
            return back()->withErrors($validator);
        }else{
            $url = preg_replace("/(lara4.com).+/", "lara4.com", url()->current(),1);
            $url = preg_replace("/http:\/\//", "", $url,1);
            $depart = Department::where('domain',$url)->first();
            $user = User::where('name', '=', Input::all()['name'])->where('partid',$depart->id)->first();
            if(!$user){
                return back()->withErrors('errors',"用户名或者密码错误");
            }else{
                $inp = array(
                    'name' => $request->all()['name'],
                    'password' => $request->all()['password'],
                    'active' => 1
                );
                if (!Auth::attempt($inp)) {
                    return back()->withErrors('errors',"用户名或者密码错误");
                }
            }
        }
        return $next($request);
    }
}
